package com.google.code.toub.waves.servlet;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;

import com.google.code.toub.waves.editor.annotation.ExtendedAnnotation;
import com.google.code.toub.waves.editor.annotation.HtmlColor;
import com.google.code.toub.waves.editor.util.BlipEditor;
import com.google.wave.api.AbstractRobot;
import com.google.wave.api.Blip;
import com.google.wave.api.event.BlipSubmittedEvent;
import com.google.wave.api.event.DocumentChangedEvent;
import com.google.wave.api.event.WaveletSelfAddedEvent;

@SuppressWarnings("serial")
public class RemoveExpiredBlipsServlet extends AbstractRobot {

	private final String robotName;

	private final BlipEditor blipEditor = new BlipEditor();

	private final ExtendedAnnotation expirationDateAnnotation = new ExtendedAnnotation(
			APP_ANNOTATION_PREFIX, EXPIRATION_DATE_ANNOTATION,
			"[Expiration date: %1$s]", HtmlColor.GRAY);

	/**
	 * Logger
	 */
	private final Logger logger = Logger.getLogger(getClass().getName());

	/**
	 * Application annotation keys prefix.
	 */
	private static final String APP_ANNOTATION_PREFIX = "toub-demo.appspot.com";

	/**
	 * Expiration date annotation key suffix.
	 */
	private static final String EXPIRATION_DATE_ANNOTATION = "expiration.date";

	private static String OAUTH_TOKEN;

	private static String SECURITY_TOKEN;

	private static String SANDBOX_DOMAIN = "wavesandbox.com";
	private static String PREVIEW_DOMAIN = "googlewave.com";

	private static String PREVIEW_RPC_URL = "http://gmodules.com/api/rpc";
	private static String SANDBOX_RPC_URL = "http://sandbox.gmodules.com/api/rpc";

	private static String OAUTH_KEY = null;
	private static String OAUTH_SECRET = null;

	private String domain = null;

	public RemoveExpiredBlipsServlet(String robotName) {
		super();
		this.robotName = robotName;

		this.domain = PREVIEW_DOMAIN;

		// FIXME OAUTH_TOKEN = System.getProperty("OAUTH_TOKEN");
		OAUTH_TOKEN = "AOijR2cCCxhxsvyLOxXzWypUGTI7a7tMWgWwnIJQ20jfhImshs6s_48EnLTVVAg6ERabpRru8__-VyHfOjDjHoRrm0JMTICNnUl2l0eyTOyyqcaI_EWknCNMKafzo7JSkVAI38b_be9sw_Z-GcvYmz6clgJ4LXWP7A==";
		// FIXME SECURITY_TOKEN = System.getProperty("SECURITY_TOKEN");
		SECURITY_TOKEN = "8161";

		// FIXME OAUTH_KEY = System.getProperty("OAUTH_KEY");
		OAUTH_KEY = "983793178314";

		// FIXME OAUTH_SECRET = System.getProperty("OAUTH_SECRET");
		OAUTH_SECRET = "McFOCM+NcOPCIbtqAuu9oA1B";
		initOauth();
	}

	public void initOauth() {

		setupVerificationToken(OAUTH_TOKEN, SECURITY_TOKEN);
		setupOAuth(OAUTH_KEY, OAUTH_SECRET, getRpcServerUrl());
		// still allows unsigned request
		setAllowUnsignedRequests(true);
	}

	public String getRpcServerUrl() {
		if (this.domain.equals(SANDBOX_DOMAIN)) {
			return SANDBOX_RPC_URL;
		}
		if (this.domain.equals(PREVIEW_DOMAIN)) {
			return PREVIEW_RPC_URL;
		}
		return null;
	}

	@Override
	protected String getRobotName() {
		return robotName;
	}

	@Override
	protected String getRobotAvatarUrl() {
		return AbstractRobot.DEFAULT_AVATAR;
	}

	@Override
	public void onDocumentChanged(DocumentChangedEvent event) {
		super.onDocumentChanged(event);
		// event.getWavelet().reply("\nonDocumentChanged");
	}

	@Override
	public void onWaveletSelfAdded(WaveletSelfAddedEvent event) {
		super.onWaveletSelfAdded(event);

		String message = "Hi everybody! I'm \"" + robotName + "\" robot (v"
				+ hashCode() + ") and I will remove your expired comments.";
		blipEditor.reply(event.getWavelet(), message, HtmlColor.NAVY);

		logger.info("The \"" + robotName + "\" robot (v" + hashCode()
				+ ") was added to the wave '" + event.getWavelet().getWaveId()
				+ "'");
		/*      */

		Blip proxyBlip = event.getBlip().proxyFor("toub");
		proxyBlip.append("\nThis is Toub proxy message...");
		Set<String> participants = new HashSet<String>();
		participants.add("n.toublanc@googlewave.com");
		event.getWavelet().submitWith(
				newWave("Robot created wave", participants));
	}

	@Override
	public void onBlipSubmitted(final BlipSubmittedEvent event) {
		super.onBlipSubmitted(event);

		// update expiration date
		expirationDateAnnotation.update(event.getBlip(),
				getNextExpirationDate());
	}

	private String getNextExpirationDate() {
		// next expiration date is in 30 seconds
		GregorianCalendar calendar = new java.util.GregorianCalendar();
		calendar.add(Calendar.SECOND, 30);

		// format the date into a comprehensive format
		DateFormat df = new SimpleDateFormat("yyyy/dd/MM HH:mm:ss");
		return df.format(calendar.getTime());
	}

}
